package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类，定时处理订单状态
 * */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 处理超时订单方法
     * */
    @Scheduled(cron = "0 * * * * ?")//每分钟执行一次
    public void processTimeoutOrder(){
        log.info("处理超时订单 {}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//当前时间减15分钟
        List<Orders> statusByTimeout = orderMapper.getStatusByTimeout(Orders.PENDING_PAYMENT,time);
        for (Orders orders : statusByTimeout) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("订单超时");
            orderMapper.update(orders);
        }
    }
    /**
     * 处理一直处于派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * *")//每天凌晨一点
    public void processDeliverOrder(){
        log.info("定时处理处于派送中的订单 {}",LocalDateTime.now());
        List<Orders> statusIsFour = orderMapper.getStatusIsFour(Orders.DELIVERY_IN_PROGRESS);
        for (Orders orders : statusIsFour) {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
            orderMapper.update(orders);
        }

    }
    /**
     * 更新订单号,订单号再次从1开始
     * */
    @Scheduled(cron = "0 0 0 * * *")//每天凌晨
    public void updateOrderNumber(){
        log.info("更新订单号，从0开始 {}",LocalDateTime.now());
        //redisTemplate.delete("orderNumber");
        redisTemplate.opsForValue().set("orderNumber",0);
    }
}
